package gdac

import (
	"database/sql/driver"
	"io"
	"strings"
	"sync/atomic"
)

type DacDBRows struct {
	daclib   *DacLib
	columns  []string
	dacquery uintptr
	n        int64
	idx      int64
}

var (
	dbrows_new_cnt  uint32
	dbrows_free_cnt uint32
)

func NewDacDBRows(daclib *DacLib) *DacDBRows {
	rval := &DacDBRows{daclib: daclib}
	atomic.AddUint32(&dbrows_new_cnt, 1)
	return rval
}

func (rc *DacDBRows) Close() error {
	atomic.AddUint32(&dbrows_free_cnt, 1)
	return nil
}

func (rc *DacDBRows) Columns() []string {
	if len(rc.columns) > 0 {
		return rc.columns
	}
	str := rc.daclib.GetQueryColumns(rc.dacquery)
	rc.columns = strings.Split(str, ",")
	return rc.columns
}

func (rc *DacDBRows) ColumnTypeDatabaseTypeName(index int) string {
	str := rc.daclib.GetQueryColumnTypeDatabaseTypeName(rc.dacquery, index)
	return str
}

func (rc *DacDBRows) Next(dest []driver.Value) error {
	if rc.idx == rc.n {
		return io.EOF
	}
	rc.daclib.GetQueryRecordValues(rc.dacquery, len(rc.columns), dest)
	rc.daclib.QueryNext(rc.dacquery)
	rc.idx++
	return nil
}
